/*
 *  求最大子数组的题，比较经典，最好的解题思路是用动态规划
 *  但是这个地方可以用到分治思想
 *
 * */

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:

    //以下是分治的思想
    struct Status {
        int iSum, mSum, lSum, rSum;
    };

    Status pushUp(Status l, Status r) {
        int iSum = l.iSum + r.iSum;
        int lSum = max(l.lSum, l.iSum + r.lSum);
        int rSum = max(r.rSum, r.iSum + l.rSum);
        int mSum = max(max(l.mSum, r.mSum), l.rSum + r.lSum);
        return (Status) {iSum, mSum, lSum, rSum};
    }

    Status get(vector<int> &nums, int l, int r) {
        if (l == r) {
            return (Status) {nums[l], nums[l], nums[l], nums[l]};
        }

        int m = (l + r) >> 1;
        Status left = get(nums, l, m);
        Status right = get(nums, m + 1, r);
        return pushUp(left, right);
    }

    int maxSubArray(vector<int> &nums) {
        return get(nums, 0, nums.size() - 1).mSum;
    }

    //以下是动态规划
    int maxSubArray2(vector<int> &nums) {
        int pre = 0, maxPos = nums[0];
        for (const auto num: nums) {
            pre = max(pre + num, num);
            maxPos = max(pre, maxPos);
        }
        return maxPos;
    }
};

int main() {

    vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    Solution solution;

    auto res = solution.maxSubArray(nums);
    cout << res << endl;

    return 0;
}